package com.atguigu.lease.common.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author yjf
 * @version 1.0
 * @description: String 转换成枚举的转换器工厂类
 * @date 2024/9/7 14:29
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {


    /**
     * @date: 2024/9/7 14:34
     * @param: [targetType]
     * @return: org.springframework.core.convert.converter.Converter<java.lang.String,T>
     * @description: spingmvc调用getConverter传入一个枚举的类对象得到一个转换器
     **/
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //1.通过枚举类对象获取枚举对象，这里是反射的知识newInstance()
                T[] enumConstants = targetType.getEnumConstants();
                //2.遍历枚举数组
                for (T enumConstant : enumConstants) {
                    if (enumConstant.getCode().equals(Integer.valueOf(source))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("非法参数异常");
            }
        };
    }
}
